package com.um.jdy.platform.shop.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.um.jdy.common.shop.code.ShopCode;
import com.um.jdy.common.shop.entity.dto.CourierDTO;
import com.um.jdy.common.shop.entity.po.Courier;
import com.um.jdy.common.shop.entity.vo.CourierVO;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.shop.service.CourierService;
import com.um.jdy.platform.shop.entity.vo.CourierErrorVO;
import com.um.jdy.platform.shop.entity.dto.CourierPageDTO;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BasePlusManager;
import com.um.springboot.starter.orm.params.ExportParams;
import com.um.springboot.starter.orm.params.ListDTO;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.*;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 管理类：物流公司表
 */
@Component
public class CourierManager extends BasePlusManager<CourierService, Courier, CourierDTO, CourierVO, CourierPageDTO, ListDTO> {

    @Transactional
    public Response<Courier> addEntity(CourierDTO dto) {

        if(service.getEntity("code",dto.getCode()) != null){
            return Response.failed(ShopCode.CourierCodeExist);
        }

        if(service.getEntity("name",dto.getName()) != null){
            return Response.failed(ShopCode.CourierNameExist);
        }

        Courier entity = UMBeanUtils.copyBean(dto,Courier.class);
        return Response.success(service.addEntity(entity));
    }

    @Transactional
    public Response<Courier> updateEntity(String id,CourierDTO dto) {

        Courier item = service.getEntity("code",dto.getCode());

        if(item != null && !StringUtil.equals(id,item.getShopCourierId())){
            return Response.failed(ShopCode.CourierCodeExist);
        }

        item = service.getEntity("name",dto.getName());
        if(item != null && !StringUtil.equals(id,item.getShopCourierId())){
            return Response.failed(ShopCode.CourierNameExist);
        }

        Courier entity = UMBeanUtils.copyBean(dto,Courier.class);
        entity.setShopCourierId(id);
        return Response.success(service.updateEntity(entity));
    }

    public Response exportCourierPage(ExportParams exportParams) {

        exportParams.getCondition().put("orderby", "sort_no asc");

        List<Courier> list = service.getListByLike(exportParams.getProperties(), exportParams.getValues(), exportParams.getRangeEntitys(),
                exportParams.getOrderNames(), exportParams.getSortOns(), exportParams.getStart(), exportParams.getLimit());

        PageParams pageParams = new PageParams();
        pageParams.setPageNo(exportParams.getPageNo());
        pageParams.setPageSize(exportParams.getPageSize());
        pageParams.setCondition(exportParams.getCondition());
        pageParams.setCustom(exportParams.getCustom());

        Map<String, String> mapFormat = new Hashtable<>();

        String fileName = "Excel" + DateUtil.getDateString(new Date(), "yyyyMMddHHmmss") + ".xls";
        String path = service.getExportFilePath(fileName);
        List<String> columns = Arrays.asList("公司名称", "公司编码", "显示序号", "是否启用");
        List<String> properties = Arrays.asList("name", "code", "sort_no", "is_enable");
        ExcelUtil.writeEntity(path, columns, list, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(), true);

        return Response.success(service.getDownFilePath(fileName));

    }

    public Response<List<CourierErrorVO>> importExcel(String path) {
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(FileUtil.getInputStream(service.getFilePath(path)));
        FileUtil.del(service.getFilePath(path));
        List<Map<String, Object>> list = reader.readAll();

        if (list.size() == 0) {
            return Response.failed("导入失败：没有可以导入的数据！");
        }

        List<CourierErrorVO> errorList = new ArrayList<>();
        for (Map item : list) {
            Courier courier = new Courier();
            courier.setName(StringUtil.getTrim(item.get("公司名称")));
            courier.setCode(StringUtil.getTrim(item.get("公司编码")));
            courier.setSortNo(StringUtil.toInt(item.get("显示序号")));
            courier.setIsEnable(YesOrNo.Yes.name().equals(StringUtil.getTrim(item.get("是否启用"))) ? "Yes" : "No");

            if (StringUtil.isEmpty(courier.getName())) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司名称不能为空！"));
                continue;
            }

            if (courier.getName().length() > 32) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司名称不能超过32个字符！"));
                continue;
            }

            if (service.getEntity("name",courier.getName()) != null) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司名称已存在！"));
                continue;
            }

            if (StringUtil.isEmpty(courier.getCode())) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司编码不能为空！"));
                continue;
            }

            if (courier.getCode().length() > 32) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司编码不能超过32个字符！"));
                continue;
            }

            if (service.getEntity("code",courier.getCode()) != null) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司编码已存在！"));
                continue;
            }

            if (!ReUtil.contains("([0-9A-Za-z])+", courier.getCode())) {
                errorList.add(new CourierErrorVO(courier.getName(), "公司编码只能是英文字母和数字！"));
                continue;
            }

            if (StringUtil.isEmpty(courier.getSortNo())) {
                errorList.add(new CourierErrorVO(courier.getName(), "显示序号不能为空！"));
                continue;
            }

            if (StringUtil.toInt(courier.getSortNo()) < 0 || StringUtil.toInt(courier.getSortNo()) > 100000) {
                errorList.add(new CourierErrorVO(courier.getName(), "显示序号只能大于0或小于100000！"));
                continue;
            }


            service.save(courier);
        }

        return Response.success(errorList);
    }


    /**
     * 查询所有物流公司列表
     * @return
     */
    public List<CourierVO> getAll(){
        List<Courier> list = service.getList("is_enable",YesOrNo.Yes.name(),"sort_no","asc");
        return UMBeanUtils.copyBeanList(list,CourierVO.class);
    }

}
